package com.changan.remote.assistant;

import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;

/**
 * <pre>
 *     @author : xujl
 *     e-mail : 597355068@qq.com
 *     time   : 2018/11/8
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class RemoteDelegate {
    private ReceiveEventListener mEventListener;
    private RemoteCallbackList<IAssisantCallback> mRemoteCallbackList = new RemoteCallbackList<>();

    public RemoteDelegate (ReceiveEventListener eventListener) {
        mEventListener = eventListener;
    }

    public IBinder getIBinder () {
        return new LocalBinder();
    }

    /**
     * 分发事件
     *
     * @param requestCode 请求编号
     * @param json 事件参数
     */
    public void dispatchEvent (int requestCode, String json) {
        final int count = mRemoteCallbackList.beginBroadcast();
        if (count == 0) {
            return;
        }
        try {
            for (int i = 0; i < count; i++) {
                final IAssisantCallback broadcastItem = mRemoteCallbackList.getBroadcastItem(i);
                if (broadcastItem.getRequestCode() == requestCode) {
                    broadcastItem.onCallback(json);
                    break;
                }
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        } finally {
            mRemoteCallbackList.finishBroadcast();
        }
    }

    class LocalBinder extends IRemoteAssisant.Stub {

        @Override
        public void registerListener (IAssisantCallback callBack) throws RemoteException {
            mRemoteCallbackList.register(callBack);
        }

        @Override
        public void unRegisterListener (IAssisantCallback callBack) throws RemoteException {
            mRemoteCallbackList.unregister(callBack);
        }

        @Override
        public void sendEvent (String json) throws RemoteException {
            mEventListener.onReceiveEvent(json);
        }
    }

    public interface ReceiveEventListener {
        void onReceiveEvent (String json);
    }
}
